<template>
  <div class="t-map-container" ref="tMapRef"> </div>
</template>

<script>
import map from './mixins/map';
import { assign } from 'lodash';
import { loadScript } from './utils/commonApi';
export default {
  name: 'TMap',
  components: {},
  props: {
    options: {
      type: Object,
      default: () => ({}),
    },
    mapKey: {
      type: String,
      default: 'b27819c88fae43c197252dee5dd8f7b1',
    },
    mapVersion: {
      type: String,
      default: '4.0',
    },
    autoInit: {
      type: Boolean,
      default: true,
    },
    wmts: {
      type: Array,
      default: () => [
        'http://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=',
        'http://t0.tianditu.gov.cn/cia_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=',
      ],
    },
  },
  data() {
    return {
      // 注意：在地图实例及图层实例初始化时，切莫将变量放入data中，这样会造成不必要的内存消耗以及效率降低
    };
  },
  mixins: [map],
  computed: {},
  created() {},
  mounted() {
    if (this.autoInit) {
      this.init();
    }
  },
  methods: {
    // 地图初始化（是否加载图层由wmts配置决定，如果不想渲染图层，则可以配置wmts为空数组）
    async init() {
      let mapConfig = assign(
        {
          // EPSG:900913(墨卡托投影); EPSG:4326(大地平面投影)
          projection: 'EPSG:900913',
          center: [116.40969, 39.89945],
          zoom: 8,
          minZoom: 5,
          maxZoom: 18,
        },
        this.options,
      );
      // 等待api脚本加载完成
      await loadScript({ key: this.mapKey, version: this.mapVersion });
      // 处理经纬度
      if (Array.isArray(mapConfig.center)) {
        const [lng, lat] = mapConfig.center;
        mapConfig.center = new window.T.LngLat(lng, lat);
      }
      // 初始化切片
      const layers = this.loadTileLayer();
      if (layers.length) {
        mapConfig.layers = layers;
      }
      // 初始化地图
      this.map = new window.T.Map(this.$refs.tMapRef, mapConfig);
    },
    // 加载切片图层
    loadTileLayer() {
      let wmtsLayer = [];
      (this.wmts || []).forEach((url, i) => {
        // 注意：配置切片时，数组索引越大，渲染的图层越靠前（由zIndex决定）
        const layer = new window.T.TileLayer(`${url}${this.mapKey}`, {
          minZoom: 1,
          maxZoom: 18,
          zIndex: i + 1,
        });
        wmtsLayer.push(layer);
      });
      return wmtsLayer;
    },
  },
};
</script>

<style lang="scss" scoped>
.t-map-container {
  min-width: 300px;
  min-height: 300px;
  width: 100%;
  height: 100%;
}
</style>
